const router = require("koa-router")();
const axios = require("axios");
const Config = require("../module/config.js");

const { appID, appSecret, SERVICE_URL } = Config;
// router.prefix("/api/users");

/**
 * @description 拼接完整的授权地址
 * @param {string} webUrl 前端调用授权前的地址（授权结束后需要返回的地址）
 * @date: 2021/9/27
 */
const getAuthUrl = (webUrl) => {
  let redirectUri = encodeURIComponent(
    `${SERVICE_URL}/wxBack?webUrl=${webUrl}`
  );
  console.log(">>>>回调", `${SERVICE_URL}/wxBack?webUrl=${webUrl}`);
  return `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appID}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo#wechat_redirect`;
};

/**
 * @description 获取accessToken和openid
 * @param {string} code 授权得到的code
 * @date: 2021/9/27
 */
const getAccessTokenByCode = async (code) => {
  let { data } = await axios.get(
    `https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appID}&secret=${appSecret}&code=${code}&grant_type=authorization_code`
  );
  return data;
};

/**
 * @description 获取微信用户信息
 * @param {string} accessToken
 * @param {string} openid 用户openid
 * @date: 2021/9/27
 */
const getUserInfo = async (accessToken, openid) => {
  let { data } = await axios.get(
    `https://api.weixin.qq.com/sns/userinfo?access_token=${accessToken}&openid=${openid}&lang=zh_CN`
  );
  return data;
};
router.get("/", async (ctx, next) => {
  ctx.status = 200;
  ctx.body = {
    code: 200,
    data: "koa2",
    msg: "success",
  };
});

router.get("/goAuth", async (ctx, next) => {
  // 拿到调用授权的前端地址
  let { webUrl } = ctx.query;
  // 拿到鉴权的完整地址
  let authUrl = getAuthUrl(webUrl);
  // 重定向
  ctx.status = 200;
  ctx.redirect(authUrl);
});

router.get("/wxBack", async (ctx, next) => {
  // 拿到code和调用授权的前端地址
  let { webUrl, code } = ctx.query;
  // 获取accessToken
  let { access_token, openid } = await getAccessTokenByCode(code);
  // 获取用户信息
  let { nickname } = await getUserInfo(access_token, openid);
  ctx.redirect(
    `${webUrl}?openid=${openid}&nickname=${nickname}`
  );
});

module.exports = router;
